<template>
  <div class="app-container">
    <!-- 开课选择卡片 -->
    <el-card>
      <div slot="header">选择开设课程</div>
      <div>
        <el-cascader
          v-model="courseId"
          :options="dropDownData.courseSchedule"
          :show-all-levels="false"
          :props="{emitPath:false}"
        />
      </div>
    </el-card>
    <!-- 作业操作按钮 -->
    <el-card style="margin-top: 10px;">
      <el-button type="success" @click="openHwCreateDialog()">新增作业</el-button>
    </el-card>

    <!-- 作业选择卡片 -->
    <el-card v-if="homeworkList && homeworkList.length > 0" style="height: 500px;overflow: auto;margin-top: 10px;">
      <el-card
        v-for="hw in homeworkList"
        :key="hw.id"
        shadow="hover"
        style="background-color: ghostwhite;margin-top: 10px;"
      >
        <el-row>
          <el-col :span="7">
            <div class="homework-icon">作业</div>
            <el-link :underline="false" @click="openHwEditDialog(hw.id)">
              <span style="margin-left: 10px;">
                {{ hw.homeworkName }}
              </span>
            </el-link>
          </el-col>
          <el-col :span="11" style="line-height: 50px;">
            <span>起止时间：{{ hw.startTime }} ~ {{ hw.endTime }}</span>
            <el-link :underline="false" @click="openHwEditDialog(hw.id)"><i class="el-icon-edit" /> </el-link>
          </el-col>
          <el-col :span="6" style="position: relative;margin-top: 5px;">
            <el-button type="danger" @click="removeHomework(hw.id)">删除作业</el-button>
            <el-button @click="openEditDialoag(hw.id)">编辑题目</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-card>
    <el-card v-else style="height: 500px;overflow: auto;margin-top: 10px;">
      <center style="font-weight: bold;margin-top: 200px;">暂无作业</center>
    </el-card>

    <!-- 作业题目编辑对话框 -->
    <el-dialog :visible.sync="editDialogSHow" width="60%" :before-close="closeEditDialog" center>
      <el-row>
        <!-- 题目编辑区域 -->
        <el-col :span="14">
          <h2 v-if="showQuesTypeIdx >= 0">{{ questionTypeTitles[showQuesTypeIdx] }}</h2>
          <h2 v-else>请选择题目</h2>
          <ChooseQuestionEdit
            v-if="showQuesTypeIdx === 0"
            :id="questionEditData.id"
            :index="questionIdx"
            :hw-id="homeworkId"
            :title="questionEditData.title"
            :options="questionEditData.options"
            :is-multiple="questionEditData.isMultiple"
            :delete-callback="deleteCallback"
            :create-callback="createCallback"
            style="margin-top: 20px;font-size: larger;"
          />
          <FillQuestionEdit
            v-if="showQuesTypeIdx === 1"
            :id="questionEditData.id"
            :index="questionIdx"
            :hw-id="homeworkId"
            :title="questionEditData.title"
            :blank-num="questionEditData.blankNum"
            :delete-callback="deleteCallback"
            :create-callback="createCallback"
            style="margin-top: 20px;font-size: larger;"
          />
          <AnswerQuestionEdit
            v-if="showQuesTypeIdx === 2"
            :id="questionEditData.id"
            :index="questionIdx"
            :hw-id="homeworkId"
            :title="questionEditData.title"
            :delete-callback="deleteCallback"
            :create-callback="createCallback"
            style="margin-top: 20px;font-size: larger;"
          />

        </el-col>
        <!-- 题目选择区域 -->
        <el-col :span="10">
          <el-card>
            <!-- 选择 -->
            <h3>{{ questionTypeTitles[0] }}</h3>
            <el-row
              v-for="(qsList,it) in chooseQuestionList"
              :key="qsList.ridx"
              :gutter="5"
              style="margin-top: 10px;"
            >
              <el-col v-for="(qs,idx) in qsList.data " :key="qs.id" :span="4">
                <el-button
                  :type="getBtnType('qsBtn-choose-',qs)"
                  style="width: 60px;text-align: center;"
                  @click="switchQuestionEdit(qs,1,it*6 + idx+1 )"
                >
                  <span v-if="qs.id!==-1">{{ it*6 + idx+1 }}</span>
                  <i v-else class="el-icon-plus" />
                </el-button>
              </el-col>
            </el-row>
            <!-- 填空 -->
            <h3>{{ questionTypeTitles[1] }}</h3>
            <el-row
              v-for="(qsList,it) in fillQuestionList"
              :key="qsList.ridx"
              :gutter="5"
              style="margin-top: 10px;"
            >
              <el-col v-for="(qs,idx) in qsList.data " :key="qs.id" :span="4">
                <el-button
                  :type="getBtnType('qsBtn-fill-',qs)"
                  style="width: 60px;text-align: center;"
                  @click="switchQuestionEdit(qs,2,it*6 + idx+1 )"
                >
                  <span v-if="qs.id!==-1">{{ it*6 + idx+1 }}</span>
                  <i v-else class="el-icon-plus" />
                </el-button>
              </el-col>
            </el-row>
            <!-- 问答 -->
            <h3>{{ questionTypeTitles[2] }}</h3>
            <el-row
              v-for="(qsList,it) in answerQuestionList"
              :key="qsList.ridx"
              :gutter="5"
              style="margin-top: 10px;"
            >
              <el-col v-for="(qs,idx) in qsList.data " :key="qs.id" :span="4">
                <el-button
                  :type="getBtnType('qsBtn-answer-',qs)"
                  style="width: 60px;text-align: center;"
                  @click="switchQuestionEdit(qs,3,it*6 + idx+1 )"
                >
                  <span v-if="qs.id!==-1">{{ it*6 + idx+1 }}</span>
                  <i v-else class="el-icon-plus" />
                </el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 作业信息编辑对话框 -->
    <el-dialog
      :visible.sync="hwEditDialogShow"
      width="30%"
      :title="isHwEdit?'作业信息编辑':'作业新增'"
      center
    >
      <el-form v-model="hwDialogData">
        <el-form-item label="作业名称" prop="homeworkName">
          <el-input v-model="hwDialogData.homeworkName" type="text" />
        </el-form-item>
        <el-form-item label="作业开始和结束时间" prop="timeGap">
          <el-date-picker
            v-model="hwDialogData.timeGap"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="closeHwEditDialog">取消</el-button>
          <el-button type="primary" @click="hwEditSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import ChooseQuestionEdit from '@/components/Work/ChooseQuestion/editable.vue'
import AnswerQuestionEdit from '@/components/Work/AnswerQuestion/editable.vue'
import FillQuestionEdit from '@/components/Work/FillQuestion/editable.vue'

import { getHwQuestionsByHomework, listHomeworkByCourse, getHomeworkById, addHomework, editHomework,
  deleteHomework } from '@/api/ms/course/teach/homework'
import { getCourseScheduleDropDownGroupByCourse } from '@/api/ms/dropdown'
import { randInt } from '@/utils/random'

let vueHook = null

const emptyChooseQues = () => { return { id: -1, title: '', options: [], isMultiple: false } }
const emptyFillQues = () => { return { id: -1, title: '' } }
const emptyAnswerQues = () => { return { id: -1, title: '', blankNum: 1 } }
export default {
  name: 'Homework',
  components: { ChooseQuestionEdit, AnswerQuestionEdit, FillQuestionEdit },
  data() {
    return {
      dropDownData: {
        // 开课候选列表
        courseSchedule: []
      },
      courseId: 1, // 当前选中的开课编号
      homeworkList: [], // 题目列表
      hwEditDialogShow: false, // 作业信息编辑对话框显示标识
      isHwEdit: true, // 是否处于作业信息编辑模式
      hwDialogData: { // 作业信息编辑框数据
        id: null, // 作业编号
        courseId: null, // 课程编号
        homeworkName: '', // 课程作业编号
        timeGap: [] // 起止时间
      },
      questionTypeTitles: ['一、选择题', '二、填空题', '三、问答题'],
      showQuesTypeIdx: -1,
      editDialogSHow: false, // 题目编辑对话框显示标识
      currentActiveBtn: '', // 当前选中的按钮下标
      homeworkId: 1, // 作业编号
      questionList: {
        chooseQues: [],
        fillQues: [],
        answerQues: []
      }, // 作业问题列表
      questionEditData: {}, // 题目编辑数据
      questionIdx: -1, // 当前显示题号
      deleteCallback: () => {
        vueHook.refreshQuestions()
        // 重置题目选择
        vueHook.showQuesTypeIdx = -1
        this.currentActiveBtn = ''
      },
      createCallback: () => {
        vueHook.refreshQuestions()
        // 重置题目选择
        vueHook.showQuesTypeIdx = -1
        this.currentActiveBtn = ''
      }
    }
  },
  computed: {
    chooseQuestionList() {
      return this.divideQuestionList(this.questionList.chooseQues)
    },
    fillQuestionList() {
      return this.divideQuestionList(this.questionList.fillQues)
    },
    answerQuestionList() {
      return this.divideQuestionList(this.questionList.answerQues)
    }
  },
  watch: {
    courseId(val) {
      this.refeshData()
    }
  },
  mounted() {
    // 获取下拉数据
    this.getDropDownData()
    // 刷新作业列表数据
    this.refeshData()
    vueHook = this
  },
  methods: {
    // 获取下拉数据
    getDropDownData() {
      // 获取开课按学院分组数据
      getCourseScheduleDropDownGroupByCourse().then(({ data }) => {
        this.dropDownData.courseSchedule = data
      })
    },
    // 打开作业信息编辑对话框
    openHwEditDialog(hwId) {
      this.isHwEdit = true
      getHomeworkById(hwId).then(({ data }) => {
        this.hwDialogData.id = hwId
        this.hwDialogData.homeworkName = data.homeworkName
        this.hwDialogData.timeGap = [data.startTime, data.endTime]
        this.hwEditDialogShow = true
      })
    },
    // 打开作业添加对话框
    openHwCreateDialog() {
      this.isHwEdit = false
      this.hwEditDialogShow = true
    },
    // 关闭作业信息编辑对话框
    closeHwEditDialog() {
      this.hwEditDialogShow = false
      this.hwDialogData = {
        id: null, // 作业编号
        courseId: null, // 课程编号
        homeworkName: '', // 课程作业编号
        timeGap: [] // 起止时间
      }
    },
    // 提交作业信息数据
    hwEditSubmit() {
      const reqData = {
        id: this.hwDialogData.id,
        homeworkName: this.hwDialogData.homeworkName,
        startTime: this.hwDialogData.timeGap[0],
        endTime: this.hwDialogData.timeGap[1]
      }
      if (this.isHwEdit) {
        editHomework(reqData).then(({ message }) => {
          this.$message.success(message)
          this.closeHwEditDialog()
          this.refeshData()
        })
      } else {
        reqData.id = null
        reqData.courseId = this.courseId
        addHomework(reqData).then(({ message }) => {
          this.$message.success(message)
          this.closeHwEditDialog()
          this.refeshData()
        })
      }
    },
    // 删除作业数据
    removeHomework(hwId) {
      this.$confirm('确认删除作业？', '删除确认').then(() => {
        deleteHomework(hwId).then(({ message }) => {
          this.$message.success(message)
          this.refeshData()
        })
      }).catch(() => {

      })
    },
    // 刷新作业表数据
    refeshData() {
      listHomeworkByCourse(this.courseId).then(({ data }) => {
        this.homeworkList = data
      })
    },
    getBtnType(prefix, qs) { // 获取题目选择按钮type样式
      const acName = prefix + qs.id
      if (acName !== this.currentActiveBtn) {
        return 'default'
      } else if (qs.id === -1) {
        return 'success'
      } else {
        return 'primary'
      }
    },
    refreshQuestions() { // 刷新作业题目列表
      getHwQuestionsByHomework(this.homeworkId).then(({ data }) => {
        this.questionList = data
        this.questionList.chooseQues.push(emptyChooseQues())
        this.questionList.fillQues.push(emptyFillQues())
        this.questionList.answerQues.push(emptyAnswerQues())
      })
    },
    openEditDialoag(hwId) {
      this.homeworkId = hwId
      // 刷新作业题目列表
      this.refreshQuestions()
      this.editDialogSHow = true
    },
    closeEditDialog() {
      this.editDialogSHow = false
      this.questionList = {
        answerQues: [emptyChooseQues()],
        fillQues: [emptyFillQues()],
        chooseQues: [emptyAnswerQues()]
      }
      this.questionEditData = {}
      this.showQuesTypeIdx = -1
      this.currentActiveBtn = ''
    },
    divideQuestionList(arr) { // 对问题列表按每6个分组
      const chunk = 6
      const res = []
      for (let i = 0; i < arr.length; i += chunk) {
        res.push({ ridx: randInt(1000, 8888), data: arr.slice(i, i + chunk) })
      }
      return res
    },
    switchQuestionEdit(qs, code, qsIdx) {
      // 刷新数据
      this.refreshQuestions()
      switch (code) {
        case 1: {
          this.questionIdx = qsIdx
          this.showQuesTypeIdx = 0
          this.currentActiveBtn = `qsBtn-choose-${qs.id}`
          this.questionEditData = qs
          break
        }
        case 2: {
          this.questionIdx = qsIdx
          this.showQuesTypeIdx = 1
          this.currentActiveBtn = `qsBtn-fill-${qs.id}`
          this.questionEditData = qs
          break
        }
        case 3: {
          this.questionIdx = qsIdx
          this.showQuesTypeIdx = 2
          this.currentActiveBtn = `qsBtn-answer-${qs.id}`
          this.questionEditData = qs
          break
        }
        default:
          break
      }
    }
  }
}

</script>

<style scoped>
  .homework-icon {
    display: inline-block;
    height: 50px;
    width: 50px;
    border-radius: 10%;
    text-align: center;
    background-color: #3A8BFF;
    color: white;
    font-weight: bold;
    line-height: 50px;
  }
</style>
